package com.swak.fx.support.snapshot;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import com.swak.fx.support.AbstractComp;
import com.swak.fx.support.FXMLView;
import com.swak.fx.support.Snapshots;
import com.swak.fx.support.ui.UIImage;
import com.swak.storage.LocalStorage;
import com.swak.utils.FileUtils;

import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Label;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;

/**
 * 创建文件的缩略图
 * 
 * @author DELL
 */
@FXMLView(title = "文件缩略图", value = "FileSnapshot.fxml", css = "FileSnapshot.css")
public class FileSnapshot extends AbstractComp {

	private UIImage image;
	@FXML
	private TextFlow name;
	private Text fileName;
	@FXML
	private Label size;

	@Override
	protected void useComputedSize() {
		this.root.setMinHeight(-1);
		this.root.setMaxHeight(-1);
		this.root.setMinWidth(-1);
		this.root.setMaxWidth(-1);
	}

	@Override
	public void initializeParts() {
		super.initializeParts();
		this.image = new UIImage();
		this.image.setPrefSize(45, 45);
		this.fileName = new Text();
		this.name.getChildren().add(fileName);
		this.addChild(this.image);
		GridPane.setMargin(image, new Insets(0, 5, 0, 0));
		GridPane.setConstraints(image, 0, 0);
		GridPane.setRowSpan(image, 2);
		this.root.setViewOrder(1);
	}

	@Override
	public void setupEventHandlers() {
		super.setupEventHandlers();
	}

	@Override
	public void setupValueChangedListeners() {
		super.setupValueChangedListeners();
	}

	/**
	 * 设置文件
	 * 
	 * @param file
	 */
	private void setFile(File file) {
		this.fileName.setText(file.getName());
		this.size.setText(FileUtils.formatFileSize(file.length()));
		this.image.image(Snapshots.getSystemImage(file));
	}

	/**
	 * 输出文件
	 * 
	 * @return
	 */
	public File output() {
		SnapshotParameters params = new SnapshotParameters();
		params.setFill(javafx.scene.paint.Color.TRANSPARENT);
		WritableImage snapshot = this.root.snapshot(params, null);
		BufferedImage image = Snapshots.fromFXImage(snapshot, null);
		File output = LocalStorage.New().randomfile("png");
		try {
			ImageIO.write(image, "png", output);
		} catch (Exception e) {
		}
		return output;
	}

	/**
	 * 创建一个文件缩略图
	 * 
	 * @param file
	 * @return
	 */
	public static FileSnapshot of(File file) {
		FileSnapshot snapshot = FileSnapshot.New(FileSnapshot.class);
		snapshot.setFile(file);
		return snapshot;
	}
}